package com.cy.pj.sys.service.impl;

import com.cy.pj.common.annotation.ClearCache;
import com.cy.pj.common.annotation.RequiredCache;
import com.cy.pj.common.exception.ServiceException;
import com.cy.pj.common.pojo.Node;
import com.cy.pj.common.utils.AssertUtils;
import com.cy.pj.sys.dao.SysCategoryDao;

import com.cy.pj.sys.pojo.SysCategory;
import com.cy.pj.sys.pojo.SysDept;
import com.cy.pj.sys.service.SysCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
@Service
public class SysCategoryServiceImpl implements SysCategoryService {

    @Autowired
    private SysCategoryDao sysCategoryDao;


    @Override
    public List<Map<String, Object>> findObjects() {
        List<Map<String, Object>> list=
                sysCategoryDao.findObjects();
        if(list==null||list.size()==0)
            throw new ServiceException("没有类目信息");
        return list;
    }
    @Override
    public List<Node> findZTreeNodes() {
        List<Node> list=
                sysCategoryDao.findZTreeNodes();
        if(list==null||list.size()==0)
            throw new ServiceException("没有类目信息");
        return list;
    }

    @ClearCache
    @Override
    public int updateObject(SysCategory sysCategory) {
        //1.合法验证

        AssertUtils.isServiceValid(sysCategory==null,"保存对象不能为空");
        AssertUtils.isServiceValid(StringUtils.isEmpty(sysCategory.getName()), "类目名称不能为空");
        int rows;
        //2.更新数据
        try{
            rows=sysCategoryDao.updateObject(sysCategory);
        }catch(Exception e){
            e.printStackTrace();
            throw new ServiceException("更新失败");
        }
        //3.返回数据
        return rows;
    }

    @Override
    public int saveObject(SysCategory sysCategory) {
        //1.合法验证

        AssertUtils.isServiceValid(sysCategory==null,"保存对象不能为空");
        AssertUtils.isServiceValid(StringUtils.isEmpty(sysCategory.getName()), "类目名称不能为空");
        //2.保存数据
        int rows=sysCategoryDao.insertObject(sysCategory);
        //if(rows==1)
        //throw new ServiceException("save error");
        //3.返回数据
        return rows;
    }
    @Override
    public int deleteObject(Integer id) {
        //1.合法性验证

        AssertUtils.isServiceValid(id==null||id<=0, "数据不合法,id="+id);
        //2.执行删除操作
        //2.1判定此id对应的菜单是否有子元素
        int childCount=sysCategoryDao.getChildCount(id);

        AssertUtils.isServiceValid(childCount>0, "此元素有子元素，不允许删除");
        //2.2判定此部门是否有用户
        //int userCount=sysUserDao.getUserCountByDeptId(id);
        //if(userCount>0)
        //throw new ServiceException("此部门有员工，不允许对部门进行删除");
        //2.2判定此部门是否已经被用户使用,假如有则拒绝删除
        //2.3执行删除操作
        int rows=sysCategoryDao.deleteObject(id);

        AssertUtils.isServiceValid(rows==0 ,"此信息可能已经不存在");
        return rows;
    }
}
